<template>
    <div>
      <!--面包屑导航区-->
      <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>商品管理</el-breadcrumb-item>
        <el-breadcrumb-item>用户列表</el-breadcrumb-item>
      </el-breadcrumb>

      <!--卡片视图区-->
      <el-card>
        <!--警告视图-->
        <el-alert title="注意：警告提示的文案" type="warning" :closable="false" show-icon>
        </el-alert>

        <!--选择商品分类区域-->
        <el-row class="cate_lp">
          <el-col >
            <span>选择商品分类：</span>
            <!--选择商品分类的级联选择框-->
            <el-cascader expand-trigger="hover"
              v-model="selectedmultiKeys"
              :options="catelist"
              :props="cateProps"
              @change="handleChange"></el-cascader>
          </el-col>
        </el-row>


        <!--tab 页面标签区-->
        <el-tabs v-model="activeName" @tab-click="handleClick">

          <!--动态面板-->
          <el-tab-pane label="动态参数" name="many">
            <el-button type="primary" size="mini" :disabled="isBtnDisabled" @click="adddialogVisible=true">添加参数</el-button>
           <!--动态参数表格0-->
            <el-table :data="manyTableData" style="width: 100%" border stripe>
              <!--展开行-->
              <el-table-column type="expand">
                <template slot-scope="scope" >
                  <el-tag v-for="(item, i) in scope.row.attr_vals" :key="i" closable @close="handleClose(scope.row,i)">{{item}}</el-tag>

                  <!--+NewTag-->
                  <el-input class="input-new-tag" v-if="scope.row.inputVisible" v-model="scope.row.inputValue" ref="saveTagInput" size="small"
                            @keyup.enter.native="handleInputConfirm(scope.row)" @blur="handleInputConfirm(scope.row)"></el-input>
                  <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>

                </template>
              </el-table-column>
              <!--索引列-->
              <el-table-column type="index" label="#"></el-table-column>
              <el-table-column prop="attr_name" label="参数名称" ></el-table-column>
              <el-table-column label="操作" >
                <template slot-scope="scope">
                  <!--修改按钮-->
                  <el-button type="primary" icon="el-icon-edit" size="mini" @click="aditFormPop(scope.row.attr_id)">编辑</el-button>
                  <!--删除按钮-->
                  <el-button type="danger" icon="el-icon-delete" size="mini" @click="deleteFormParams(scope.row.attr_id)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-tab-pane>

          <!--静态面板-->
          <el-tab-pane label="静态属性" name="only" >
            <el-button type="primary" size="mini" :disabled="isBtnDisabled" @click="adddialogVisible=true">添加属性</el-button>
            <!--静态属性表格-->
            <el-table :data="onlyTableData" style="width: 100%" border stripe>
              <!--展开行-->
              <el-table-column type="expand">
                <template slot-scope="scope" >
                  <el-tag v-for="(item, i) in scope.row.attr_vals" :key="i" closable @close="handleClose(scope.row,i)">{{item}}</el-tag>
                  <!--+NewTag-->
                  <el-input class="input-new-tag" v-if="scope.row.inputVisible" v-model="scope.row.inputValue" ref="saveTagInput" size="small"
                    @keyup.enter.native="handleInputConfirm(scope.row)" @blur="handleInputConfirm(scope.row)"></el-input>
                  <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)" >+ New Tag</el-button>

                </template>
              </el-table-column>
              <!--索引列-->
              <el-table-column type="index" label="#"></el-table-column>
              <el-table-column prop="attr_name" label="属性名称" ></el-table-column>
              <el-table-column label="操作" >
                <template slot-scope="scope">
                  <!--修改按钮-->
                  <el-button type="primary" icon="el-icon-edit" size="mini" @click="aditFormPop(scope.row.attr_id)">编辑</el-button>
                  <!--删除按钮-->
                  <el-button type="danger" icon="el-icon-delete" size="mini" @click="deleteFormParams(scope.row.attr_id)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-tab-pane>
        </el-tabs>
      </el-card>


      <!--添加参数和属性的对话框-->
      <el-dialog
        :title="'添加'+ titleText"
        :visible.sync="adddialogVisible"
        width="50%" @close="addDialogClosed">

        <el-form :model="addForm" :rules="addFormRules" ref="ruleFormRef" label-width="100px" >
          <el-form-item :label="titleText" prop="attr_name">
            <el-input v-model="addForm.attr_name"></el-input>
          </el-form-item>
        </el-form>

        <span slot="footer" class="dialog-footer">
    <el-button @click="adddialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="addParams">确 定</el-button>
  </span>
      </el-dialog>

      <!--修改参数和属性的对话框-->
      <el-dialog
        :title="'修改'+ titleText"
        :visible.sync="aditDialogVisible"
        width="50%" @close="aditDialogClosed">

        <el-form :model="aditForm" :rules="aditFormRules" ref="aditRuleFormRef" label-width="100px" >
          <el-form-item :label="titleText" prop="attr_name">
            <el-input v-model="aditForm.attr_name"></el-input>
          </el-form-item>
        </el-form>

        <span slot="footer" class="dialog-footer">
    <el-button @click="aditDialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="aditParams(aditForm.attr_id)">确 定</el-button>
  </span>
      </el-dialog>

    </div>
</template>

<script>
    export default {
        name: "Params",
      data(){
          return{
           CategetParams:{
             type:2,
             pagenum:1,
             pagesize:6
           },
            //控制添加新标签的切换
            //inputVisible: false,
            //inputValue: '',
            //给商品分类赋值
            catelist:[],
            //级联选择框的配置对象
            cateProps:{
              value:'cat_id',
              label:'cat_name',
              children:'children'
            },
            //级联选择框双向绑定到的数组
            selectedmultiKeys:[],
            //默认table
            activeName:"only",
            //动态参数的数据
            manyTableData:[],
            //静态属性的数据
            onlyTableData:[],
            //添加对话框的F/T
            adddialogVisible:false,
            //添加参数的表单数据对象
            addForm:{ attr_name:'' },
            //添加表单数据的验证规则
            addFormRules:{
              attr_name:[{ required: true, message: '请输入参数名称', trigger: 'blur' }]
            },
            //修改对话框的显示与隐藏
            aditDialogVisible:false,
            //修改的表单数据
            aditForm:{ },
            //修改表单的验证规则
            aditFormRules:{
              attr_name:[{ required: true, message: '请输入参数名称', trigger: 'blur' }]
            }
          }
      },
      created() {
       this.getCateList()
      },
      methods:{
       //获取商品分类列表
        async getCateList() {
        const{data:res}= await this.axios.get('categories')
          if(res.meta.status !== 200){
            return this.$memege.error('获取商品分类失败！')
          }
          this.catelist = res.data
          console.log(this.catelist);
        },
        /*级联选择框选择变化触发函数*/
        handleChange(){
            this.getParamsData()
       },
        //tab切换事件
        handleClick(){
         this.getParamsData()
          console.log(this.activeName);
        },
        //这里尤其要注意的地方是无论级联选择器还是切换参数发生变化都要发起请求获取参数，所以这些参数变化要单独抽离出来供两者使用
       async getParamsData(){
          if (this.selectedmultiKeys.length !== 3){
            //this.selectedmultiKeys.length = []
            this.selectedmultiKeys = []
            this.manyTableData = []
            this.onlyTableData = []
            return
          }

          //根据所选分类的id和所在的面板发起请求获取参数
          const {data:res}= await this.axios.get(`categories/${this.cateId}/attributes`,{params:{sel:this.activeName}})
          if (res.meta.status !== 200){
            return this.$memege.error('获取参数列表失败!')
          }

          //本来是字符串，经过循环重新赋值变成数组
          res.data.forEach(item=>{
            item.attr_vals = item.attr_vals?item.attr_vals.split(' '):[]
            /*重要！！！！在循环每一项数组的时候给每个数组添加控制文本框的属性*/
            //控制+NewTag与文本框的显示与隐藏
            item.inputVisible = false
            //文本框双向绑定值
            item.inputValue = ''
            console.log(item.attr_id);
          })
         if(this.activeName==="many"){
            this.manyTableData = res.data
          }else {
            this.onlyTableData = res.data
          }
        },
        //关闭添加表单对话框
        addDialogClosed(){
          this.$refs.ruleFormRef.resetFields()

          this.adddialogVisible = false
        },
        //点击确定按钮添加参数
        addParams(){
          this.$refs.ruleFormRef.validate(async valid =>{
            if (!valid) return console.log('111')
           const {data:res}= await this.axios.post(`categories/${this.cateId}/attributes`,{
              attr_name:this.addForm.attr_name,
              attr_sel:this.activeName
            })

            if (res.meta.status !== 201) {
              this.$memege.error('添加失败！')
            }
            this.$memege.success('添加成功！')
            this.adddialogVisible = false
          })
        },
        //点击编辑，查询参数
       async aditFormPop(val){
         const {data:res}= await this.axios.get(`categories/${this.cateId}/attributes/${val}`,{params: {attr_sel:this.activeName}})
         if (res.meta.status !== 200) {
           return this.$memege.error('获取参数信息失败！')
         }
          this.aditForm = res.data
          this.aditDialogVisible = true

       },
        //点击确认修改表单数据
      aditParams(val){
        this.$refs.aditRuleFormRef.validate(async valid=>{
          if (!valid)return
          const {data:res} = await this.axios.put(`categories/${this.cateId}/attributes/${val}`,{attr_name:this.aditForm.attr_name,attr_sel:this.activeName})
          if (res.meta.status !== 200){
            return this.$memege.error('修改参数失败！')
          }
          this.$memege.success('修改参数成功！')
          this.aditDialogVisible = false
        })

        },

   //点击取消对话框重置修改表单
        aditDialogClosed(){
          this.$refs.aditRuleFormRef.resetFields()
        },
       async deleteFormParams(val){
          const deleteParamInfo = await this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }).catch(err=>err)
         //console.log(deleteParamInfo);

           if (deleteParamInfo === 'cancel') {
            return this.$memege.info('已取消删除表单参数！')
           }
          const {data:res}= await this.axios.delete(`categories/${this.cateId}/attributes/${val}`)
         if (res.meta.status !== 200){
          return this.$memege.error('删除失败！')
         }
         this.$memege.success('删除成功')
         this.getParamsData()
       },
        //点击+ newTag切换输入文本框
        showInput(val){
          val.inputVisible = true

          //让文本框自动获得焦点
          //$nextTick()在页面渲染之后才指定函数的回调
          this.$nextTick(_ =>{
            this.$refs.saveTagInput.$refs.input.focus()
          })
        },
        //文本框失去焦点或者按下enter都会触发
       handleInputConfirm(val){
          //trim()可以去除字符串两边的空格
          if (val.inputValue.trim().length === 0 ) {
            val.inputValue = ''
            val.inputVisible = false
            return
          }
          //如果没有return则输入真实内容需要后续处理,为了防止前后有空格加trim()

          val.attr_vals.push(val.inputValue.trim())
          val.inputValue = ''
          val.inputVisible = false

         this.SaveAttrVals(val)
       },
        //把标签保存起来
       async SaveAttrVals(val){
          const{data:res} = await this.axios.put(`categories/${this.cateId}/attributes/${val.attr_id}`,
            //attr_vals:val.attr_vals.join(' ')可以获得一个数组
            {attr_name:val.attr_name,attr_sel:this.activeName,attr_vals:val.attr_vals.join(' ')})
          if (res.meta.status !== 200){
            this.$memege.error('更新标签失败！')
          }
          console.log(res.data);
        },
        //删除对应的参数tag,
       async handleClose(val,i){
          //用i做索引，splice删除一项，妙！！！
            val.attr_vals.splice(i,1)
         this.SaveAttrVals(val)
      /*const {data:res} =  await this.axios.delete(`categories/${this.cateId}/attributes/${val.attr_id}`)
          if (res.meta.status !== 200){
            this.$memege.error('删除参数失败！')
          }
          this.$memege.success('删除参数成功！')
         console.log(res);*/
       }
      },
      computed:{
          //未选择三级分类则禁用按钮
        isBtnDisabled(){
          if ( this.selectedmultiKeys.length !== 3){
            return true
          }
          return false
        },
        /*获取分类id*/
        cateId(){
          if (this.selectedmultiKeys.length !== 3){
            return null
          }
          return this.selectedmultiKeys[2]
        },
        //动态计算标题的文本
        titleText(){
          if (this.activeName === "many") {
            return '动态参数'
          }
          return '静态属性'
        }
      }
    }
</script>

<style scoped>
.cate_lp{margin: 15px 0}
  .el-tag{margin: 10px}
  .input-new-tag{width: 100px}
</style>
